package at.ac.tuwien.mg.service;

import java.util.ArrayList;
import java.util.List;

import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;

import at.ac.tuwien.mg.bean.Offer;
import at.ac.tuwien.mg.bean.Supplier;
import at.ac.tuwien.mg.wh.dto.ItemDTO;
import at.ac.tuwien.mg.bean.Item;

public class AutomaticSupplierRequests implements JavaDelegate {
	
	@Override
	public void execute(DelegateExecution de) throws Exception {
		Supplier supplier = (Supplier)de.getVariable("supplier");
		System.out.println("Automatic Supplier request for supplier: " + supplier.getName());
		
		List<Item> itemList = new ArrayList<Item>();
		
		System.out.println("items we want to order:");
		ArrayList<ItemDTO> items = (ArrayList<ItemDTO>) de.getVariable("toOrder");	
		ItemDTO a;
		for(ItemDTO i : items) {			
			itemList.add(new Item(i.getName(), i.getNumber()));
			System.out.println("id:" + i.getCatalogId() +" amount: " + i.getNumber());
		}
		
		Offer offer = new Offer(supplier, itemList);
		offer.setProcessInstanceId(de.getProcessInstanceId());
		offer.setReturnAdress("http://localhost:9998/offerListener/receiveOffer");
		supplier.sendOffer(offer);

		//add one more to the count of automaticRequests
		int automaticRequests = (Integer) de.getVariable("automaticRequests");
		automaticRequests++;
		de.setVariable("automaticRequests",automaticRequests);
		
	}

}
